import 'package:winkai/db/db_ext.dart';
import 'package:winkai/ext/ext.dart';
import 'package:drift/drift.dart';
import 'package:winkai/helper/user_helper.dart';

import '../database.dart';
import '../tables/user_tb.dart';

part 'user_dao.g.dart';

@DriftAccessor(tables: [UserTb])
class UserDao extends DatabaseAccessor<RootDatabase> with _$UserDaoMixin {
  UserDao(super.attachedDatabase);

  Future<int> insertOrUpdate({
    required String id,
    required String nickname,
    required String avatar,
    int age = 0,
    String? renderStyle,
    String? aboutMe,
    List<String>? greetings,
  }) {
    var greetingStr = greetings?.toJsonString ?? '';
    return into(rootDb.userTb).insertOnConflictUpdate(UserTbCompanion.insert(
      accountId: UserHelper().userId,
      id: id,
      age: age.toDrifitNullSafeValue,
      renderStyle: renderStyle.toDrifitNullSafeValue,
      aboutMe: aboutMe.toDrifitNullSafeValue,
      nickname: nickname.toDrifiteValue,
      avatar: avatar.toDrifiteValue,
      greetings: greetingStr.toDrifiteValue,
    ));
  }

  Future<int> updateById(
    String id, {
    String? nickname,
    String? avatar,
  }) {
    return (update(userTb)
          ..where((tbl) =>
              tbl.accountId.equals(UserHelper().userId) & tbl.id.equals(id)))
        .write(UserTbCompanion(
      nickname: nickname != null ? Value(nickname) : const Value.absent(),
      avatar: avatar != null ? Value(avatar) : const Value.absent(),
    ));
  }

  Future<UserTbData?> selectSingleOrNull(String id) {
    return (select(userTb)..where((tbl) => tbl.accountExpr & tbl.id.equals(id)))
        .getSingleOrNull();
  }
}
